<template>
  <div class="app" @keydown="handleKeyDown" tabindex="0"> 
    <header class="app-header">
      <h1>我的画布</h1>
      <div class="toolbar">
        <button
          @click="undoAction"
          :disabled="!canvasStore.canUndo"   
          class="undo-btn"
          title="撤销 (Ctrl/Cmd+Z)"
        >
          撤销
        </button>
        <button
          @click="redoAction"
          :disabled="!canvasStore.canRedo"  
          class="redo-btn"
          title="重做 (Ctrl/Cmd+Shift+Z / Ctrl/Cmd+Y)"
        >
          重做
        </button>

        <button @click="addRectangle">矩形</button>
        <button @click="addCircle">圆形</button>
        <button @click="addTriangle">三角形</button>
        <button @click="addText" class="text-btn">文本</button>

        <button @click="triggerImageUpload" class="image-btn">
          图片
        </button>
        <input 
          type="file" 
          ref="fileInput"
          accept="image/png,image/jpeg,image/jpg"
          @change="handleImageUpload"
          style="display: none"
        >

        <button @click="resetView" class="view-btn">重置</button>
        <div class="zoom-info">
          {{ Math.round(viewport.scale * 100) }}%
        </div>
        <button 
          @click="deleteSelected" 
          :disabled="!hasSelection"
          class="delete-btn"
        >
          删除
        </button>
      </div>
    </header>
    <main class="app-main">
      <CanvasRenderer />
      <Toolbar />
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import CanvasRenderer from './components/CanvasRenderer.vue';
import Toolbar from './components/Toolbar.vue'; 
import { useCanvasStore } from './stores/canvas';
import type { 
  RectangleElement, 
  CircleElement, 
  TriangleElement, 
  TextElement,
  ImageElement 
} from './types/canvas';

const canvasStore = useCanvasStore();
const fileInput = ref<HTMLInputElement>();

// 触发文件选择
const triggerImageUpload = (): void => {
  fileInput.value?.click();
};

// 处理图片上传
const handleImageUpload = (event: Event): void => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  
  if (!file) return;

  if (!file.type.startsWith('image/')) {
    console.error('请选择图片文件！'); 
    return;
  }

  if (file.size > 5 * 1024 * 1024) {
    console.error('图片大小不能超过5MB！');
    return;
  }

  const reader = new FileReader();
  
  reader.onload = (e) => {
    const result = e.target?.result as string;
    if (result) {
      addImageElement(result);
    }
  };
  
  reader.onerror = () => {
    console.error('图片读取失败，请重试！');
  };
  
  reader.readAsDataURL(file);
  target.value = '';
};

// 生成唯一ID的辅助函数
const generateId = (): string => 'element_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

// 添加图片元素到画布
const addImageElement = (src: string): void => {
  const img = new Image();
  img.onload = () => {
    // 计算初始尺寸（刚上传到画布时的尺寸）
    const initialWidth = img.width > 300 ? 300 : img.width;
    const initialHeight = img.width > 300 ? (img.height * 300) / img.width : img.height;
    
    const newImage: ImageElement = {
      id: generateId(),
      type: 'image',
      x: 100,
      y: 100,
      width: initialWidth, // 使用初始尺寸
      height: initialHeight,
      originalWidth: img.width,
      originalHeight: img.height,
      initialWidth: initialWidth, // 保存初始尺寸
      initialHeight: initialHeight,
      src,
      filter: 'none',
      opacity: 1,
      borderWidth: 0,
      borderColor: '#000000',
      selected: false,
      zIndex: 0
    };
    canvasStore.addElement(newImage);
  };
  img.onerror = () => console.error('图片加载失败');
  img.src = src;
};

// 计算属性：视口状态
const viewport = computed(() => canvasStore.viewport);

// 计算属性：是否有选中的元素
const hasSelection = computed((): boolean => {
  return canvasStore.selectedElements().length > 0;
});

// 添加矩形的方法
const addRectangle = (): void => {
  const newRectangle: RectangleElement = {
    id: generateId(),
    type: 'rectangle',
    x: 100,
    y: 100,
    width: 200,
    height: 150,
    background: '#ff6b6b',
    borderWidth: 0,
    borderColor: '#000000',
    selected: false, 
    zIndex: 0 
  };
  
  canvasStore.addElement(newRectangle);
};

// 添加圆形的方法
const addCircle = (): void => {
  const newCircle: CircleElement = {
    id: generateId(),
    type: 'circle',
    x: 150,
    y: 150,
    width: 120,
    height: 120,
    background: '#4ecdc4', 
    borderWidth: 0,
    borderColor: '#000000',
    selected: false,
    zIndex: 0 
  };
  
  canvasStore.addElement(newCircle);
};

// 添加三角形的方法
const addTriangle = (): void => {
  const newTriangle: TriangleElement = {
    id: generateId(),
    type: 'triangle',
    x: 200,
    y: 200,
    width: 150,
    height: 130,
    background: '#45b7d1', 
    borderWidth: 0,
    borderColor: '#000000',
    selected: false,
    zIndex: 0 
  };
  
  canvasStore.addElement(newTriangle);
};

// 新增：添加文本元素
const addText = (): void => {
  const newText: TextElement = {
    id: generateId(),
    type: 'text',
    x: 250,
    y: 250,
    width: 120,
    height: 40,
    selected: false,
    zIndex: 0, 
    content: '双击编辑文本',
    fontSize: 16,
    fontFamily: 'Arial',
    color: '#000000',
    background: 'transparent',
    bold: false,
    italic: false,
    underline: false,
    textAlign: 'left',      
    strikethrough: false, // 默认无删除线   
  };
  canvasStore.addElement(newText);
};

// 重置视图
const resetView = (): void => {
  canvasStore.resetViewport();
};

// 删除选中的元素
const deleteSelected = (): void => {
  if (hasSelection.value) {
    canvasStore.deleteSelectedElements();
  }
};

// --- ⚡ 撤销/重做操作 ⚡ ---

const undoAction = (): void => {
  const success = canvasStore.undo();
  if (!success) {
    console.warn('无法撤销：撤销栈为空');
  }
};

const redoAction = (): void => {
  const success = canvasStore.redo();
  if (!success) {
    console.warn('无法重做：重做栈为空');
  }
};

// --- ✨ 样式切换辅助函数 (之前缺失的部分) ✨ ---
const toggleTextStyle = (property: 'bold' | 'italic' | 'underline'): void => {
  const selected = canvasStore.selectedElements();
  
  selected.forEach(element => {
    // 只有文本元素才响应这些快捷键
    if (element.type === 'text') {
      // 强制类型断言，告诉 TS 这是一个 TextElement
      const textElement = element as TextElement;
      
      // 取反当前状态 (true -> false, false -> true)
      const newValue = !textElement[property];
      
      // 更新 Store
      canvasStore.updateElement(element.id, {
        [property]: newValue
      });
    }
  });
};

// 键盘事件处理 
const handleKeyDown = (event: KeyboardEvent): void => {
  // 边界处理：快捷键冲突 - 检查是否在输入框中
  const activeElement = document.activeElement;
  const isInputFocused = activeElement?.tagName === 'INPUT' || activeElement?.tagName === 'TEXTAREA';
  
  if (isInputFocused) {
    return; 
  }

  const isMetaOrCtrl = event.metaKey || event.ctrlKey;
  
  // 撤销 (Ctrl+Z)
  if (isMetaOrCtrl && event.key.toLowerCase() === 'z' && !event.shiftKey) {
    event.preventDefault();
    undoAction();
  }
  // 重做 (Ctrl+Shift+Z 或 Ctrl+Y)
  else if (isMetaOrCtrl && ((event.key.toLowerCase() === 'z' && event.shiftKey) || event.key.toLowerCase() === 'y')) {
    event.preventDefault();
    redoAction();
  }
  
  // Delete 键或 Backspace 键删除选中元素
  if ((event.key === 'Delete' || event.key === 'Backspace') && hasSelection.value) {
    event.preventDefault(); 
    deleteSelected();
  }
  
  // Ctrl+C 复制
  if (isMetaOrCtrl && event.key === 'c') {
    event.preventDefault();
    const success = canvasStore.copySelectedElements();
    if (success) console.log('复制成功');
  }
  
  // Ctrl+V 粘贴
  if (isMetaOrCtrl && event.key === 'v') {
    event.preventDefault();
    const success = canvasStore.pasteElements();
    if (success) console.log('粘贴成功');
  }

  // Ctrl+B 加粗
  if (isMetaOrCtrl && (event.key === 'b' || event.key === 'B')) {
    event.preventDefault(); 
    toggleTextStyle('bold'); 
  }

  // Ctrl+I 斜体
  if (isMetaOrCtrl && (event.key === 'i' || event.key === 'I')) {
    event.preventDefault();
    toggleTextStyle('italic'); 
  }

  // Ctrl+U 下划线
  if (isMetaOrCtrl && (event.key === 'u' || event.key === 'U')) {
    event.preventDefault(); 
    toggleTextStyle('underline'); 
  }

  // Ctrl + +/- 缩放
  if (isMetaOrCtrl && (event.key === '=' || event.key === '+' || event.key === 'Equal')) {
    event.preventDefault();
    if (hasSelection.value) canvasStore.scaleSelectedElements(1.1); 
  }

  if (isMetaOrCtrl && event.key === '-') {
    event.preventDefault();
    if (hasSelection.value) canvasStore.scaleSelectedElements(0.9); 
  }
};

onMounted(() => {
  canvasStore.loadFromLocalStorage();
  canvasStore.loadClipboardFromLocalStorage();
});
</script>

<style>
/* 重置默认样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

#app {
  width: 100%;
  height: 100%;
}

.app {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 0; 
  outline: none; 
}

.app-header {
  padding: 0rem 1rem;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.app-header h1 {
  font-size: 2.5rem;   
  margin: 10px;   
}

.app-main {
  flex: 1;
  overflow: hidden;
  margin: 0 20px 20px 20px; 
  background: white; 
  border-radius: 8px;   
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); 
}

.toolbar {
  display: flex;
  gap: 10px; 
}

/* 通用按钮样式 */
.toolbar button {
  padding: 0.5rem 1rem;
  background: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  outline: none; /* 移除点击时的黑框 */
}

.toolbar button:focus {
  outline: none; /* 移除焦点时的黑框 */
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3); /* 添加自定义焦点样式 */
}

.toolbar button:hover:not(:disabled) {
  background: #357abd;
  transform: translateY(-1px);
}

/* --- 撤销/重做按钮样式 --- */
.undo-btn, .redo-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex; 
  align-items: center;
  gap: 4px;
  outline: none; /* 移除点击时的黑框 */
}

.undo-btn:focus,
.redo-btn:focus {
  outline: none; /* 移除焦点时的黑框 */
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3); /* 添加自定义焦点样式 */
}

.undo-btn {
  background: #4a90e2; 
  color: white;
}

.undo-btn:hover:not(:disabled) {
  background: #357abd;
  transform: translateY(-1px);
}

.redo-btn {
  background: #2ecc71; 
  color: white; 
}

.redo-btn:hover:not(:disabled) {
  background: #27ae60;
  transform: translateY(-1px);
}

.undo-btn:disabled,
.redo-btn:disabled {
  opacity: 0.5; 
  cursor: not-allowed;
  transform: none;
}

.undo-btn .icon, .redo-btn .icon {
  font-size: 16px;
}

.view-btn {
  background: #27ae60 !important;
  margin-left: 10px;
}

.view-btn:hover {
  background: #219653 !important;
}

.image-btn {
  background: #e67e22 !important; 
}

.image-btn:hover {
  background: #d35400 !important;
}

.zoom-info {
  padding: 0.5rem 1rem;
  background: #34495e;
  color: white;
  border-radius: 4px;
  font-size: 14px;
  font-family: monospace;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 60px;
  text-align: center;
}

.toolbar button:disabled {
  background: #cccccc;
  cursor: not-allowed;
  opacity: 0.6;
}

.text-btn {
  background: #9b59b6 !important;
}

.text-btn:hover {
  background: #8e44ad !important;
}

.delete-btn {
  background: #e74c3c !important; 
  margin-left: 10px; 
}

.delete-btn:hover:not(:disabled) {
  background: #c0392b !important; 
}
</style>